/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Yusuke Yamamoto nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.hertz.appr.pojo;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hertz.appr.http.Parameter;
import com.hertz.appr.util.Configuration;

/**
 * Controlls pagination
 *
 * @author Yusuke Yamamoto - yusuke at mac.com
 */
public class Paging implements java.io.Serializable {
	private Logger log = Logger.getLogger(Paging.class);
	private Byte QQ_PAGE_FLAG_FIRST = 0;
	/*
	 * 逆时针
	 */
	private Byte QQ_PAGE_FLAG_COUNTERCLOCKWISE = 1;
	/**
	 * 顺时针
	 */
	private Byte QQ_PAGE_FLAG_CLOCKWISE = 2;
	
    /*
     * 顺时针翻页 or 逆时针翻页
     * 首页为null
     * 顺时针翻页为true
     */
    private Boolean nextOrPrevious = null;
    /*
     * qq:		reqnum, 每次请求记录的条数（1-20条）
     * sina:	count，默认值20，最大值200。 	单页返回的记录条数。 
     */
    private int pageSize = 50;
    
    public final static int pageSize4Sina = 200;
    /**
     * 边缘值
     * 顺时针翻页时，返回内容 > border
     * 逆时针翻页时，返回内容 < or = border
     * 统一用微博id做为border的值
     */
    private Long border = 0L;
    
    private String provider;
    private static final long serialVersionUID = -3285857427993796670L;
    private Integer pageNum4Sina = 1;

    /**
     * 默认为第一页
     * qq: 		page = 0
     * sina:	page = 1
     * 初始化pagesize,qq=20,sina=200
     * @param provider
     */
    public Paging(String provider) {
    	this.provider = provider;
    	pageSize = Configuration.getIntProperty("max_pagesize_" + provider);
    	nextOrPrevious = null;//第一页
    }

    public Paging(String provider,Boolean nextOrPrevious,Long since) {
    	this.provider = provider;
    	this.nextOrPrevious = nextOrPrevious;
    	pageSize = Configuration.getIntProperty("max_pagesize_" + provider);
    	if(nextOrPrevious == null){//第一页，防止空指针
    		border = Long.MAX_VALUE;//上限，返回小于等于border的微博。
		}else {
			border = since;
		}
    }
    
    public boolean isFirstPage(){
    	if(nextOrPrevious == null)
    		return true;
    	else 
    		return false;
    }
    
    public List<Parameter> getQueryParams(){
    	List<Parameter> list = new ArrayList<Parameter>();
    	list.add(getCountQueryParam());
    	Parameter pageFlagP = getNextOrPreviousParam();
    	if(pageFlagP != null)
    		list.add(pageFlagP);
    	Parameter borderP = getBorderQueryParam();
    	if(borderP != null){
    		list.add(borderP);
    	}
    	return list;
    }
    
    public void nextPage(){
    	nextOrPrevious = true;
    }
    
    public void previousPage(){
    	nextOrPrevious = false;
    }

    public int getPageSize() {
        return pageSize;
    }
    
    public void setPageSize(int pageSize) {
        if (pageSize < 1) {
            throw new IllegalArgumentException("count should be positive integer. passed:" + pageSize);
        }
        this.pageSize = pageSize;
    }

    public Parameter getCountQueryParam(){
    	if(provider.equals(Configuration.QQ_PROVIDER)){
    		return new Parameter("reqnum", String.valueOf(pageSize));
    	}else{
    		return new Parameter("count", String.valueOf(pageSize));
    	}
    }
    
	public String getProvider() {
		return provider;
	}

	public void setProvider(String provider) {
		this.provider = provider;
	}
	
	/**
	 * 参考qq api,本页起始时间（第一页 0，继续：根据返回记录时间决定）
	 * pageflag 分页标识（0：第一页，1：向下翻页，2向上翻页）
	 * pagetime 第一页 时填0,继续向下翻页，填上一次请求返回的最后一条微博时间，翻页用
	 * reqnum 每次请求记录的条数（1-20条）
	 * 向下翻页时pagetime是当前页面最后一条微博时间
	 * 向上翻页时pagetime是当前页面第一条微博时间
	 * @return
	 */
	public Parameter getBorderQueryParam(){
		if(isFirstPage()){
			if(provider.equalsIgnoreCase(Configuration.QQ_PROVIDER))
				return new Parameter("pagetime", String.valueOf(Long.MAX_VALUE));
			else
				return new Parameter("max_id", String.valueOf(Long.MAX_VALUE));
		}else{
			if(provider.equalsIgnoreCase(Configuration.QQ_PROVIDER)){
				return new Parameter("pagetime", String.valueOf(this.border));
			}else{
				 if(nextOrPrevious){//顺时针
					 return new Parameter("since_id", String.valueOf(this.border));
				 }else
					 return new Parameter("max_id", String.valueOf(this.border));
			}
		}
	}

	public Parameter getNextOrPreviousParam(){
		if(provider.equalsIgnoreCase(Configuration.QQ_PROVIDER)){
			if(isFirstPage())
				return new Parameter("pageflag", String.valueOf(this.QQ_PAGE_FLAG_FIRST));
			else if(nextOrPrevious)//顺时针
				return new Parameter("pageflag", String.valueOf(this.QQ_PAGE_FLAG_CLOCKWISE));
			else//逆时针
				return new Parameter("pageflag", String.valueOf(this.QQ_PAGE_FLAG_COUNTERCLOCKWISE));
		}
		else
			return new Parameter("page", pageNum4Sina.toString());
	}
	
	public void setBorder(long border){
		this.border = border;
	}
	
	public void nextPageNum4Sina(){
		pageNum4Sina++;
	}
	
	public void setPageNum4Sina(Integer pageNum){
		this.pageNum4Sina = pageNum;
	}
}
